package mdt.figure;

import org.tigris.gef.base.Layer;
import org.tigris.gef.presentation.ArrowHeadNone;
import org.tigris.gef.presentation.Fig;
import org.tigris.gef.presentation.FigPoly;
import org.tigris.gef.presentation.Handle;
import mdt.model.MDTMessage;

import java.awt.*;

/**
 * Created by lambert on 2016/7/14.
 */
public class FigFailedMessage extends FigMessage{
	private float offset = 0.65f;


	private static final long serialVersionUID = 4618044978326422412L;

	public FigFailedMessage(MDTMessage edge, Layer lay) {
		super(edge, lay);
		setDestArrowHead(ArrowHeadNone.TheInstance);
	}

	public void setFig(Fig f) {
		FigPoly fp = new FigPoly() {
			public void paint(Graphics g) {
				_npoints--;
				super.paint(g);
				_npoints++;

				Font f = g.getFont();
				Color c = g.getColor();
				g.setFont(new Font("Times Roman", Font.PLAIN, 28));
				g.setColor(Color.red);
				FontMetrics fm = g.getFontMetrics();
				int height = fm.getHeight();

				int x = _xpoints[_npoints - 2];
				int y = _ypoints[_npoints - 2];
				if (_xpoints[0] > x) {
					x -= fm.stringWidth("X");
				}

				g.drawString("X", x, y + height / 2 - 6);
				g.setFont(f);
				g.setColor(c);
			}

			public void cleanUp() {
				if (_npoints > 3) {
					super.cleanUp();
				}
			}

			public void moveVertex(Handle h, int x, int y, boolean ov) {
				super.moveVertex(h, x, y, ov);
				if (_npoints == 3) { // two points
					offset = (1.0f * _xpoints[1] - _xpoints[0]) / (_xpoints[2] - _xpoints[0]);
				}
			}

		};
		Polygon polygon = ((FigPoly)f).getPolygon();
		if (polygon.npoints == 2) {
			polygon.npoints = 3;
			int[] xps = polygon.xpoints;
			int[] yps = polygon.ypoints;
			polygon.xpoints = new int[] {xps[0], (int)(xps[0] + (xps[1] - xps[0]) * offset), xps[1]};
			polygon.ypoints = new int[] {yps[0], (int)(yps[0] + (yps[1] - yps[0]) * offset), yps[1]};
		}
		fp.setPolygon(polygon);

		fp.setLineColor(f.getLineColor());
		fp.setFilled(false);
		fp.setDashed(true);

		super.setFig(fp);
	}

	public void paint(Graphics g) {
		super.paint(g);
	}


	protected Fig makeEdgeFig() {
		FigPoly res = new FigPoly(Color.black) {

		};
		res.setRectilinear(false);
		res.setFixedHandles(1);
		res.setFilled(false);
		return res;
	}

	public void computeRouteImpl() {
		super.computeRouteImpl();

		FigPoly fp = (FigPoly)getFig();
		if (fp.getNumPoints() == 3) {
			Point p0 = fp.getPoint(0);
			Point p2 = fp.getPoint(2);
			fp.setPoints(new Point[] {
					p0, new Point((int)(p0.x + (p2.x - p0.x) * offset), (int)(p0.y + (p2.y - p0.y) * offset)), p2});
		}

	}


}
